#include "stdafx.h"
#include "./io3ds.h"

#define ZIP_3DS_PATH "objs"

IO3ds::IO3ds()
: m_zipFile(ZIP_3DS_PATH)
{
	memset(&m_io, 0, sizeof(m_io));

	m_io.self = &m_zipFile;
	m_io.seek_func = IO3ds::SeekFunc;
	m_io.tell_func = IO3ds::TellFunc;
	m_io.read_func = IO3ds::ReadFunc;
	m_io.write_func = IO3ds::WriteFunc;
	m_io.log_func = NULL;
}

IO3ds::~IO3ds()
{

}

Lib3dsFile* IO3ds::FileOpen(string strFile)
{
	if (!m_zipFile.OpenFile(strFile))
	{
		return NULL;
	}

	Lib3dsFile* file = lib3ds_file_new();
	if (!file)
	{
		m_zipFile.CloseFile();
		return NULL;
	}

	if (!lib3ds_file_read(file, &m_io))
	{
		m_zipFile.CloseFile();
		free(file);
		return NULL;
	}

	m_zipFile.CloseFile();
	return file;
}

void IO3ds::FileClose(Lib3dsFile* pFile)
{
	lib3ds_file_free(pFile);
}

size_t IO3ds::ReadFile(string strFile, byte* buffer, size_t size)
{
	if (!m_zipFile.OpenFile(strFile))
	{
		return NULL;
	}

	if (!buffer)
	{
		//get file length
		return m_zipFile.ReadFile(NULL, 0);
	}

	size_t rb = m_zipFile.ReadFile(buffer, size);

	m_zipFile.CloseFile();

	return rb;
}

long IO3ds::SeekFunc(void *self, long offset, Lib3dsIoSeek origin)
{
	ZipFile* pZip = reinterpret_cast<ZipFile*>(self);
	return pZip->SeekFile(offset, static_cast<IOStub::IoSeek>(origin));
}

long IO3ds::TellFunc(void *self)
{
	ZipFile* pZip = reinterpret_cast<ZipFile*>(self);
	return pZip->TellFile();
}

size_t IO3ds::ReadFunc(void *self, void *buffer, size_t size)
{
	ZipFile* pZip = reinterpret_cast<ZipFile*>(self);
	return pZip->ReadFile(static_cast<byte*>(buffer), size);
}

size_t IO3ds::WriteFunc(void *self, const void *buffer, size_t size)
{
	ZipFile* pZip = reinterpret_cast<ZipFile*>(self);
	return pZip->WriteFile(static_cast<const byte*>(buffer), size);
}